package com.heatup.apt.api.controller;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.heatup.apt.api.service.CourseService;
import com.heatup.apt.api.service.CourseSignService;
import com.heatup.apt.api.service.OrderService;
import com.heatup.apt.common.constants.CourseConstants;
import com.heatup.apt.common.constants.ErrorCodeConstants;
import com.heatup.apt.common.constants.OrderContants.OrderType;
import com.heatup.apt.common.util.JsonTools;
import com.heatup.apt.common.util.JsonUtils;
import com.heatup.apt.common.util.RequestTools;
import com.heatup.apt.common.util.ResponseTools;
import com.heatup.apt.model.api.ApiResultModel;
import com.heatup.apt.model.api.course.CourseDetailModel;
import com.heatup.apt.model.api.course.CourseResultModel;
import com.heatup.apt.model.api.course.CourseSignModel;
import com.heatup.apt.model.order.OrderInfo;
import com.heatup.apt.model.user.UserInfo;

/**
 * Created by b3st9u on 16/8/20.
 */
@RequestMapping(value = "/course")
@Controller
public class CourseController extends BaseController {
    protected static final Logger log = LoggerFactory.getLogger(CourseController.class);

    @Autowired
    private CourseService courseService;

    @Autowired
    private OrderService orderService;

    @Autowired
    private CourseSignService courseSignService;

    //课程详情
    @ResponseBody
    @RequestMapping(value = "/get2", method = {RequestMethod.POST, RequestMethod.GET})
    private String getCourseResult(HttpServletRequest request) {
        int course_id = RequestTools.RequestInt(request, "id", 0);
        String callback = RequestTools.RequestString(request, "callback", "");
        ApiResultModel<CourseResultModel> apiResultModel = new ApiResultModel<>(this.isLogined());
        String msg = "";
        UserInfo userInfo = this.getUserInfo();
        try {
            CourseResultModel courseResultModel = courseService.queryCourseById(course_id);
            apiResultModel.setRet(ApiResultModel.RET_SUCCESS);
            if (courseResultModel == null || courseResultModel.getId() == null) {
                msg = ErrorCodeConstants.Code.COURSE_NOT_FOUND.getMessage();
            }
            courseResultModel.setBookType("0");
			// 如果是会员，则需要判断是否已经预订过该课程，预订过后不允许重复预订。
			if (userInfo.getLevel().intValue() ==2 && (courseResultModel.getCourseType()
					.equals(CourseConstants.CourseType.team_course.getType())
					|| courseResultModel.getCourseType().equals(CourseConstants.CourseType.fun_camp.getType()))) {
				if (orderService.isBookCourseForUser(course_id, userInfo.getId())) {
					courseResultModel.setBookType("1");
				} else {
					courseResultModel.setBookType("0");
				}
			}


			courseResultModel.setUserLevel(userInfo.getLevel().toString());
            apiResultModel.setMsg(msg);
            apiResultModel.setData(courseResultModel);
        } catch (Exception e) {
            log.error(ErrorCodeConstants.Code.SYSTEM_ERROR_EXCEPTION.getMessage() + e.toString() + e.getCause(),e);
            apiResultModel.setRet(ApiResultModel.RET_ERROR);
            apiResultModel.setErrorCode(ErrorCodeConstants.Code.SYSTEM_ERROR_EXCEPTION.getCode());
            apiResultModel.setMsg(ErrorCodeConstants.Code.SYSTEM_ERROR_EXCEPTION.getMessage() + e.toString());
        }
        return ResponseTools.CallBackResultJsonP(JsonTools.jsonSer(apiResultModel), callback);
    }

    /**
     * API-课程详情(团课/私教/檬营) blank Mar.13.2017
     *
     * @param id 课程 ID
     * @return 课程详情
     */
    @RequestMapping(value = "/get")
    @ResponseBody
    private String courseDetail(Integer id, String callback) {

        ApiResultModel<CourseDetailModel> apiResultModel = new ApiResultModel<>(this.isLogined());
        UserInfo userInfo = this.getUserInfo();
        if (userInfo == null || userInfo.getId() == null) {
            apiResultModel.setMsg("API 查询课程详情出错 - - - - >> UserInfo 或 userId 为 null");
            return ResponseTools.CallBackResultJsonP(JsonTools.jsonSer(apiResultModel), callback);
        }
        try {
            CourseDetailModel courseDetailModel = courseService.queryCourseByCourseId(id, userInfo.getId());
            courseDetailModel.setBookType("0");
            
            // 如果是会员，则需要判断是否已经预订过该课程，预订过后不允许重复预订。
            /**
            if (userInfo.getLevel() == 2 && (courseDetailModel.getCourseType()
                    .equals(CourseConstants.CourseType.team_course.getType())
                    || courseDetailModel.getCourseType().equals(CourseConstants.CourseType.fun_camp.getType()))) {
                if (orderService.isBookCourseForUser(id, userInfo.getId())) {
                    courseDetailModel.setBookType("1");
                } else {
                    courseDetailModel.setBookType("0");
                }
            }*/
            courseDetailModel.setUserLevel(getUserInfo().getLevel().toString());
            apiResultModel.setData(courseDetailModel);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("查询课程详情出错--blank-->>" + e.toString() + e.getCause());
        }
        apiResultModel.setRet(ApiResultModel.RET_SUCCESS);

        return ResponseTools.CallBackResultJsonP(JsonTools.jsonSer(apiResultModel), callback);
    }

    /**
     * 获取私教课签到数据
     *
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/sign_info", method = {RequestMethod.POST, RequestMethod.GET})
    private String getSignInfo(HttpServletRequest request) {
        int orderId = RequestTools.RequestInt(request, "orderId", 0);
        String callback = RequestTools.RequestString(request, "callback", "");
        ApiResultModel<CourseSignModel> apiResultModel = new ApiResultModel<>(this.isLogined());

        //未登陆
        if (!isLogined()) {
            apiResultModel.setRet(ApiResultModel.RET_ERROR);
            apiResultModel.setErrorCode(ErrorCodeConstants.Code.USER_NOT_LOGIN.getCode());
            apiResultModel.setMsg(ErrorCodeConstants.Code.USER_NOT_LOGIN.getMessage());
            return ResponseTools.CallBackResultJsonP(JsonTools.jsonSer(apiResultModel), callback);
        }

        String msg = "";
        try {
            OrderInfo orderInfo = orderService.getOrderById(orderId);

            if (orderInfo == null) {
                apiResultModel.setRet(ApiResultModel.RET_ERROR);
                apiResultModel.setErrorCode(ErrorCodeConstants.Code.ORDER_NOT_FIND.getCode());
                apiResultModel.setMsg(ErrorCodeConstants.Code.ORDER_NOT_FIND.getMessage());
                return ResponseTools.CallBackResultJsonP(JsonTools.jsonSer(apiResultModel), callback);
            }

            if (orderInfo.getOrderType() != OrderType.pt.getIndex()
            	&& orderInfo.getOrderType() != OrderType.physical_examination.getIndex()
            	&& orderInfo.getOrderType() != OrderType.secret_experience.getIndex()) {
                apiResultModel.setRet(ApiResultModel.RET_ERROR);
                apiResultModel.setErrorCode(ErrorCodeConstants.Code.COURSE_TYPE_WRONG.getCode());
                apiResultModel.setMsg(ErrorCodeConstants.Code.COURSE_TYPE_WRONG.getMessage());
                return ResponseTools.CallBackResultJsonP(JsonTools.jsonSer(apiResultModel), callback);
            }

            CourseSignModel model = courseService.querySignInfo(orderInfo, this.getUserId());

            apiResultModel.setRet(ApiResultModel.RET_SUCCESS);
            apiResultModel.setData(model);
        } catch (Exception e) {
            e.printStackTrace();
            log.error(ErrorCodeConstants.Code.SYSTEM_ERROR_EXCEPTION.getMessage() + e.toString() + e.getCause(),e);
            apiResultModel.setRet(ApiResultModel.RET_ERROR);
            apiResultModel.setErrorCode(ErrorCodeConstants.Code.SYSTEM_ERROR_EXCEPTION.getCode());
            msg = ErrorCodeConstants.Code.SYSTEM_ERROR_EXCEPTION.getMessage() + e.getMessage();
        }
        apiResultModel.setMsg(msg);
        return ResponseTools.CallBackResultJsonP(JsonTools.jsonSer(apiResultModel), callback);
    }

    /**
     * 私教课签到
     *
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/sign", method = {RequestMethod.POST, RequestMethod.GET})
    private String sign(HttpServletRequest request) {
        int orderId = RequestTools.RequestInt(request, "orderId", 0);
        String callback = RequestTools.RequestString(request, "callback", "");
        ApiResultModel<CourseSignModel> apiResultModel = new ApiResultModel<>(this.isLogined());

        //未登陆
        if (!isLogined()) {
            apiResultModel.setRet(ApiResultModel.RET_ERROR);
            apiResultModel.setMsg(ErrorCodeConstants.Code.USER_NOT_LOGIN.getMessage());
            return ResponseTools.CallBackResultJsonP(JsonTools.jsonSer(apiResultModel), callback);
        }

        String msg = "";
        try {
            OrderInfo orderInfo = orderService.getOrderById(orderId);

            if (orderInfo == null) {
                apiResultModel.setRet(ApiResultModel.RET_ERROR);
                apiResultModel.setMsg(ErrorCodeConstants.Code.ORDER_NOT_FIND.getMessage());
                return ResponseTools.CallBackResultJsonP(JsonTools.jsonSer(apiResultModel), callback);
            }

            if (orderInfo.getOrderType() != OrderType.pt.getIndex()
            		&& orderInfo.getOrderType() != OrderType.physical_examination.getIndex()
                	&& orderInfo.getOrderType() != OrderType.secret_experience.getIndex()) {
                apiResultModel.setRet(ApiResultModel.RET_ERROR);
                apiResultModel.setErrorCode(ErrorCodeConstants.Code.COURSE_TYPE_WRONG.getCode());
                apiResultModel.setMsg(ErrorCodeConstants.Code.COURSE_TYPE_WRONG.getMessage());
                return ResponseTools.CallBackResultJsonP(JsonTools.jsonSer(apiResultModel), callback);
            }

            int courseNumber = courseService.sign(orderInfo, this.getUserId());
            if (courseNumber < 0) {
                apiResultModel.setRet(ApiResultModel.RET_ERROR);
                apiResultModel.setErrorCode(ErrorCodeConstants.Code.COURSE_NOT_SIGN_FIND.getCode());
                apiResultModel.setMsg(ErrorCodeConstants.Code.COURSE_NOT_SIGN_FIND.getMessage());
            } else {

                //签到成功后返回已签到数据
                CourseSignModel model = courseService.querySignInfo(orderInfo, this.getUserId());

                //Map<String,Object> map = new HashMap<String,Object>();
                //map.put("periodNumber", courseNumber);

                apiResultModel.setRet(ApiResultModel.RET_SUCCESS);
                apiResultModel.setData(model);
            }

        } catch (Exception e) {
            e.printStackTrace();
            log.error(ErrorCodeConstants.Code.SYSTEM_ERROR_EXCEPTION.getMessage() + e.toString() + e.getCause(),e);
            apiResultModel.setRet(ApiResultModel.RET_ERROR);
            apiResultModel.setErrorCode(ErrorCodeConstants.Code.SYSTEM_ERROR_EXCEPTION.getCode());
            msg = ErrorCodeConstants.Code.SYSTEM_ERROR_EXCEPTION.getMessage() + e.getMessage();

        }
        apiResultModel.setMsg(msg);
        return ResponseTools.CallBackResultJsonP(JsonTools.jsonSer(apiResultModel), callback);
    }

    /**
     * 课程用户签到详情
     *
     * @param courseId 课程ID
     * @param callback 回调
     * @return
     */
    @RequestMapping(value = "/getCourseUserSignInfo")
    @ResponseBody
    public String getCourseUserSignInfo(@RequestParam Integer courseId,
                                        @RequestParam(defaultValue = "") String callback) {

        ApiResultModel apiResultModel = new ApiResultModel();
        if (getUserInfo() == null) {
            apiResultModel.setErrorCode(ErrorCodeConstants.Code.USER_NOT_LOGIN.getCode());
            apiResultModel.setMsg(ErrorCodeConstants.Code.USER_NOT_LOGIN.getMessage());
        } else {
            UserInfo userInfo = getUserInfo();
            try {
                apiResultModel = courseSignService.courseUserSignInfo(courseId, userInfo.getId());
            } catch (Exception e) {
                e.printStackTrace();
                log.error("用户端 查询用户签到详情出错 blank - -! ---> " + e.toString() + e.getCause(),e);
            }
        }
        apiResultModel.setLogined(isLogined());
        return ResponseTools.CallBackResultJsonP(JsonUtils.obj2Json(apiResultModel), callback);
    }
    
    /**
     * 查询私教咨询课程详情
     * @return
     */
    @ResponseBody
    @RequestMapping( value = "/get_consult_course")
    public String getconsultCourse(HttpServletRequest request) {
    	String callback = RequestTools.RequestString(request, "callback", "");
        ApiResultModel<Object> apiResultModel = new ApiResultModel<>(this.isLogined());
        Map<String,Object> resultMap = new HashMap<>();
        try {
        	resultMap = courseService.queryConsultCourseDetail();
        	apiResultModel.setData(resultMap);
        	apiResultModel.setRet(ApiResultModel.RET_SUCCESS);
        	apiResultModel.setMsg("查询成功！");
		} catch (Exception e) {
			// TODO: handle exception
			apiResultModel.setData("");
        	apiResultModel.setRet(ApiResultModel.RET_ERROR);
        	apiResultModel.setMsg("查询失败！");
        	log.error("================ getconsultCourse error:"+e.toString()+e.getCause(),e);
        	
		}
        return ResponseTools.CallBackResultJsonP(JsonTools.jsonSer(apiResultModel), callback);
    }

}